package com.ctsi.framework.schema.manager.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootVersion;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: zhangjw
 * @Date: 2018/9/13 00:13
 * @Description:
 */
public class LiquibaseEnvironmentPostProcessor implements EnvironmentPostProcessor {

    private static final Logger LOGGER = LoggerFactory.getLogger(LiquibaseEnvironmentPostProcessor.class);
    /**
     * Post-process the given {@code environment}.
     *
     * @param environment the environment to post-process
     * @param application the application to which the environment belongs
     */
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        String liquibaseProperty = getLiquibaseProperty();
        if (!environment.containsProperty(liquibaseProperty)) {
            LOGGER.warn("Liquibase has not been explicitly enabled or disabled. Overriding default from Spring Boot from `true` to `false`. "
                    + "ctsi-cloud-framework pulls in Liquibase, but does not use the Spring Boot configuration for it. "
                    + "If you are using it you would need to set `{}` to `true` by yourself", liquibaseProperty);
            Map<String, Object> source = new HashMap<>();
            source.put(liquibaseProperty, false);
            environment.getPropertySources().addLast(new MapPropertySource("ctsicloud-liquibase-override", source));
        }
    }

    protected String getLiquibaseProperty() {
        String liquibaseProperty = "liquibase.enabled";
        String springBootVersion = SpringBootVersion.getVersion();
        if (springBootVersion.startsWith("2")) {
            liquibaseProperty = "spring." + liquibaseProperty;
        }
        return liquibaseProperty;
    }
}
